<?php
/**
 * Installer mainfile creation page
 *
 * @copyright		The XOOPS project http://www.xoops.org/
 * @license			http://www.fsf.org/copyleft/gpl.html GNU General Public License (GPL)
 * @package			installer
 * @since			2.0.18
 * @version			$Id: page_configsave.php 596 2006-06-30 03:14:03Z skalpa $
 *
 * @author			Haruki Setoyama  <haruki@planewave.org>
 * @author			Kazumi Ono <webmaster@myweb.ne.jp>
 * @author			Skalpa Keo <skalpa@xoops.org>
 * @author			dugris <dugris@frxoops.org>
**/

require_once 'common.inc.php';
if ( !defined('XOOPS_INSTALL') ) { die('XOOPS Custom Installation die'); }

$wizard->setPage( 'configsave' );
$pageHasForm = true;
$pageHasHelp = false;

$vars =& $_SESSION['settings'];

if ( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
	$error = '';
	$mainfile_dist = $vars['ROOT_PATH'] . '/mainfile.dist.php';
	if ( $wizard->trust_path ) {
		$mainfile_dist = $vars['ROOT_PATH'] . '/mainfile.dist.fr.php';
	}
	if ( !copy( $mainfile_dist, $vars['ROOT_PATH'] . '/mainfile.php' ) ) {
		$error = ERR_COPY_MAINFILE;
	} else {
		clearstatcache();

		$rewrite = array( 'GROUP_ADMIN' => 1, 'GROUP_USERS' => 2, 'GROUP_ANONYMOUS' => 3 );
		$rewrite = array_merge( $rewrite, $vars );
		if ( ! $file = fopen( $vars['ROOT_PATH'] . '/mainfile.php', "r" ) ) {
			$error = ERR_READ_MAINFILE;
		} else {
			$content = fread( $file, filesize( $vars['ROOT_PATH'] . '/mainfile.php' ) );
			fclose($file);

			foreach( $rewrite as $key => $val ) {
				if ( is_int($val) && preg_match("/(define\()([\"'])(XOOPS_$key)\\2,\s*([0-9]+)\s*\)/", $content ) ) {
					$content = preg_replace( "/(define\()([\"'])(XOOPS_$key)\\2,\s*([0-9]+)\s*\)/",
													 "define( 'XOOPS_$key', $val )", $content );
				} elseif( preg_match( "/(define\()([\"'])(XOOPS_$key)\\2,\s*([\"'])(.*?)\\4\s*\)/", $content ) ) {
					$val = addslashes( $val );
					$content = preg_replace( "/(define\()([\"'])(XOOPS_$key)\\2,\s*([\"'])(.*?)\\4\s*\)/",
													 "define( 'XOOPS_$key', '" . str_replace( '$', '\$',$val ) . "' )", $content );
				} else {
					//$this->error = true;
					//$this->report .= _NGIMG.sprintf( ERR_WRITING_CONSTANT, "<b>$val</b>")."<br />\n";
				}
			}
			if ( !$file = fopen( $vars['ROOT_PATH'] . '/mainfile.php', "w" ) ) {
				$error = ERR_WRITE_MAINFILE;
			} else {
				if ( fwrite( $file, $content ) == -1 ) {
					$error = ERR_WRITE_MAINFILE;
				}
				fclose($file);
			}
		}
	}
	if ( empty( $error ) ) {
		$_SESSION['Login'] = true;
		$wizard->redirectToPage( '+1' );
		exit();
	}
	$content = '<div class="errorMsg">' . $error . '</div>';
	include 'install_tpl.php';
	exit();
}

ob_start();

echo "<div class='x2-note confirmMsg'>" . READY_SAVE_MAINFILE . "</div>
		<ul class='log'>";

foreach ( $vars as $k => $v ) {
	echo "<li><strong>XOOPS_$k</strong> " . IS_VALOR . " $v</li>";
}
echo "</ul>";

$content = ob_get_contents();
ob_end_clean();
include 'install_tpl.php';

?>